<template>
	<div class="wrapper">
		<!-- header部分 -->
		<header>
			<p>提现</p>
		</header>

		<!-- 提现表单 -->
		<div class="withdraw-form">
			<!-- 余额显示 -->
			<div class="balance-display">
				<h3>可用余额</h3>
				<p class="balance-amount">¥{{ walletData.balance?.toFixed(2) || '0.00' }}</p>
				<p class="balance-hint">提现金额+手续费不能超过可用余额（含透支额度）</p>
			</div>

			<!-- 提现金额输入 -->
			<div class="amount-section">
				<h3>提现金额</h3>
				<div class="amount-input">
					<span class="currency">¥</span>
					<input
						type="number"
						v-model="withdrawAmount"
						placeholder="请输入提现金额"
						min="0.01"
						step="0.01"
						@input="calculateFee"
					/>
				</div>
			</div>

			<!-- 手续费规则 -->
			<div class="fee-rules">
				<h3>手续费规则</h3>
				<div class="rules-info">
					<p>提现手续费：{{ (feeConfig.feeRate * 100).toFixed(0) }}%</p>
					<p class="fee-note">注：手续费从钱包可用余额中扣除，实际到账金额 = 提现金额，余额扣除 = 提现金额 + 手续费</p>
				</div>
			</div>

			<!-- 提现计算结果 -->
			<div class="withdraw-summary" v-if="withdrawAmount > 0 && isValidAmount">
				<div class="summary-item">
					<span>提现金额:</span>
					<span>¥{{ withdrawAmount }}</span>
				</div>
				<div class="summary-item">
					<span>手续费:</span>
					<span class="fee-text">¥{{ feeAmount.toFixed(2) }}</span>
				</div>
				<div class="summary-item">
					<span>余额扣除:</span>
					<span class="deduct-text">¥{{ totalDeductAmount.toFixed(2) }}</span>
				</div>
				<div class="summary-item total">
					<span>实际到账:</span>
					<span class="total-text">¥{{ actualAmount.toFixed(2) }}</span>
				</div>
			</div>

			<!-- 提现方式选择 -->
			<div class="withdraw-methods">
				<h3>提现方式</h3>
				<ul class="method-list">
					<li @click="selectWithdrawMethod('bank')" :class="{ selected: selectedMethod === 'bank' }">
						<i class="fa fa-university"></i>
						<span>银行卡提现</span>
						<i class="fa fa-check-circle"></i>
					</li>
					<li @click="selectWithdrawMethod('alipay')" :class="{ selected: selectedMethod === 'alipay' }">
						<img src="../assets/alipay.png" alt="支付宝提现">
						<i class="fa fa-check-circle"></i>
					</li>
					<li @click="selectWithdrawMethod('wechat')" :class="{ selected: selectedMethod === 'wechat' }">
						<img src="../assets/wechat.png" alt="微信提现">
						<i class="fa fa-check-circle"></i>
					</li>
				</ul>
			</div>

			<!-- 提现备注 -->
			<div class="withdraw-notes">
				<textarea
					v-model="withdrawRemark"
					placeholder="请输入提现备注（选填）"
					maxlength="100"
				></textarea>
				<p class="note-count">{{ withdrawRemark.length }}/100</p>
			</div>
		</div>

		<!-- 操作按钮 -->
		<div class="action-buttons">
			<button class="cancel-btn" @click="goBack">取消</button>
			<button
				class="confirm-btn"
				@click="confirmWithdraw"
				:disabled="isProcessing || !isValidAmount"
			>
				<span v-if="isProcessing">处理中...</span>
				<span v-else>确认提现</span>
			</button>
		</div>

		<!-- 加载状态 -->
		<div v-if="isLoading" class="loading">
			<p>加载中...</p>
		</div>

		<!-- 错误提示 -->
		<div v-if="errorMsg" class="error-msg">
			<p>{{ errorMsg }}</p>
		</div>

		<!-- 底部菜单 -->
		<Footer></Footer>
	</div>
</template>

<script>
import Footer from '../components/Footer.vue';
import axios from 'axios';

export default {
	name: 'WalletWithdraw',
	components: {
		Footer
	},
	data() {
		return {
			walletData: {
				balance: 0,
				frozenBalance: 0,
				overdraftLimit: 0,
				totalBalance: 0
			},
			withdrawAmount: '',
			withdrawRemark: '',
			selectedMethod: 'bank',
			feeConfig: {
				feeRate: 0.10 // 根据后端 RewardRuleInitializer.java，提现手续费费率为 0.10 (10%)
			},
			feeAmount: 0,
			actualAmount: 0,
			totalDeductAmount: 0, // 总扣除金额（提现金额 + 手续费）
			isLoading: false,
			isProcessing: false,
			errorMsg: ''
		};
	},
	computed: {
		isValidAmount() {
			const amount = parseFloat(this.withdrawAmount) || 0;
			if (amount <= 0 || amount < 0.01) {
				return false;
			}
			// 根据新的后端逻辑，手续费从余额中扣除
			// 需要检查：balance + overdraftLimit >= (提现金额 + 手续费)
			const fee = parseFloat((amount * this.feeConfig.feeRate).toFixed(2));
			const totalDeduct = amount + fee; // 总扣除金额
			const availableBalance = (this.walletData.balance || 0) + (this.walletData.overdraftLimit || 0);
			return totalDeduct <= availableBalance;
		}
	},
	methods: {
		async loadWalletData() {
			this.isLoading = true;
			this.errorMsg = '';
			try {
				const token = localStorage.getItem('id_token');
				if (!token) {
					this.$router.push('/login');
					return;
				}

				const response = await axios.get('wallet/balance', {
					headers: {
						'Authorization': `Bearer ${token}`
					}
				});

				if (response.data.success && (response.data.code === 200 || response.data.code === 0)) {
					this.walletData = response.data.data;
				} else {
					this.errorMsg = response.data.message || '获取钱包信息失败';
				}
			} catch (error) {
				this.errorMsg = '网络错误，请重试';
			} finally {
				this.isLoading = false;
			}
		},
		calculateFee() {
			const amount = parseFloat(this.withdrawAmount) || 0;

			if (amount <= 0) {
				this.feeAmount = 0;
				this.actualAmount = 0;
				this.totalDeductAmount = 0;
				return;
			}

			// 根据后端 RewardRule.calculateFee 逻辑计算手续费
			// 手续费 = amount * rewardRate，四舍五入到2位小数（HALF_UP）
			// 后端费率：0.10 (10%)
			const fee = amount * this.feeConfig.feeRate;
			this.feeAmount = parseFloat(fee.toFixed(2));

			// 根据新的后端逻辑：手续费从余额中扣除
			// 实际到账 = 提现金额（手续费从余额中扣除，不影响实际到账）
			this.actualAmount = parseFloat(amount.toFixed(2));

			// 总扣除金额 = 提现金额 + 手续费
			this.totalDeductAmount = parseFloat((amount + this.feeAmount).toFixed(2));
		},
		selectWithdrawMethod(method) {
			this.selectedMethod = method;
		},
		async confirmWithdraw() {
			if (!this.isValidAmount) return;

			this.isProcessing = true;
			this.errorMsg = '';

			try {
				const token = localStorage.getItem('id_token');
				if (!token) {
					this.$router.push('/login');
					return;
				}

				const response = await axios.post('wallet/withdraw', null, {
					headers: {
						'Authorization': `Bearer ${token}`
					},
					params: {
						amount: parseFloat(this.withdrawAmount),
						remark: this.withdrawRemark || `${this.selectedMethod}提现`
					},
					timeout: 10000
				});

				if (response.data.success && (response.data.code === 200 || response.data.code === 0)) {
					// 提现成功，跳转回钱包首页
					this.$router.push({
						path: '/wallet',
						query: { success: 'true', message: '提现成功' }
					});
				} else {
					this.errorMsg = response.data.message || '提现失败';
				}
			} catch (error) {
				this.errorMsg = '网络错误，请重试';
			} finally {
				this.isProcessing = false;
			}
		},
		goBack() {
			this.$router.push('/wallet');
		}
	},
	mounted() {
		this.loadWalletData();
	}
};
</script>

<style scoped>
.wrapper {
	padding-bottom: 60px;
	min-height: 100vh;
	background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
	background-attachment: fixed;
}

header {
	background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
	color: #fff;
	padding: 5vw 4vw;
	text-align: center;
	box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
	position: relative;
	overflow: hidden;
}

header::before {
	content: '';
	position: absolute;
	top: -50%;
	left: -50%;
	width: 200%;
	height: 200%;
	background: radial-gradient(circle, rgba(255, 255, 255, 0.1) 0%, transparent 70%);
	animation: pulse 3s ease-in-out infinite;
}

@keyframes pulse {
	0%, 100% {
		transform: scale(1);
		opacity: 0.5;
	}
	50% {
		transform: scale(1.1);
		opacity: 0.8;
	}
}

header p {
	margin: 0;
	font-size: 4.5vw;
	font-weight: 600;
	position: relative;
	z-index: 1;
	text-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
}

.withdraw-form {
	background: #fff;
	margin: 4vw 3vw;
	border-radius: 3vw;
	padding: 5vw;
	box-shadow: 0 8px 32px rgba(0, 0, 0, 0.15);
	transition: transform 0.3s, box-shadow 0.3s;
}

.withdraw-form:hover {
	transform: translateY(-2px);
	box-shadow: 0 12px 40px rgba(0, 0, 0, 0.2);
}

/* 余额显示 */
.balance-display {
	text-align: center;
	margin-bottom: 5vw;
	padding: 5vw 4vw;
	background: linear-gradient(135deg, #f0f4ff 0%, #e6f0ff 100%);
	border-radius: 2.5vw;
	border: 2px solid #91d5ff;
	box-shadow: 0 4px 16px rgba(102, 126, 234, 0.15);
	position: relative;
	overflow: hidden;
}

.balance-display::before {
	content: '';
	position: absolute;
	top: -50%;
	right: -50%;
	width: 100%;
	height: 100%;
	background: radial-gradient(circle, rgba(102, 126, 234, 0.1) 0%, transparent 70%);
	animation: rotate 10s linear infinite;
}

@keyframes rotate {
	from { transform: rotate(0deg); }
	to { transform: rotate(360deg); }
}

.balance-display h3 {
	margin: 0 0 3vw 0;
	font-size: 4vw;
	color: #667eea;
	font-weight: 600;
	position: relative;
	z-index: 1;
}

.balance-amount {
	margin: 0 0 2vw 0;
	font-size: 8vw;
	font-weight: 700;
	color: #667eea;
	text-shadow: 0 2px 8px rgba(102, 126, 234, 0.3);
	position: relative;
	z-index: 1;
}

.balance-hint {
	margin: 0;
	font-size: 3vw;
	color: #666;
	position: relative;
	z-index: 1;
	line-height: 1.5;
}

/* 金额输入 */
.amount-section h3 {
	margin: 0 0 4vw 0;
	font-size: 4.5vw;
	color: #333;
	font-weight: 600;
	display: flex;
	align-items: center;
}

.amount-section h3::before {
	content: '';
	width: 4px;
	height: 4vw;
	background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
	border-radius: 2px;
	margin-right: 2vw;
}

.amount-input {
	display: flex;
	align-items: center;
	border: 2px solid #e0e0e0;
	border-radius: 2vw;
	padding: 4vw 3vw;
	margin-bottom: 4vw;
	background: linear-gradient(135deg, #f8f9fa 0%, #ffffff 100%);
	transition: all 0.3s;
}

.amount-input:focus-within {
	border-color: #667eea;
	box-shadow: 0 4px 16px rgba(102, 126, 234, 0.2);
	transform: translateY(-2px);
}

.currency {
	font-size: 5.5vw;
	color: #667eea;
	margin-right: 2vw;
	font-weight: 700;
}

.amount-input input {
	flex: 1;
	border: none;
	outline: none;
	font-size: 5vw;
	color: #333;
	font-weight: 600;
	background: transparent;
}

.amount-input input::placeholder {
	color: #ccc;
	font-weight: normal;
}

/* 手续费规则 */
.fee-rules h3 {
	margin: 5vw 0 4vw 0;
	font-size: 4.5vw;
	color: #333;
	font-weight: 600;
	display: flex;
	align-items: center;
}

.fee-rules h3::before {
	content: '';
	width: 4px;
	height: 4vw;
	background: linear-gradient(135deg, #ff9800 0%, #f57c00 100%);
	border-radius: 2px;
	margin-right: 2vw;
}

.rules-info {
	background: linear-gradient(135deg, #fff3cd 0%, #ffeaa7 100%);
	border: 2px solid #ffd54f;
	border-radius: 2.5vw;
	padding: 4vw;
	box-shadow: 0 4px 16px rgba(255, 152, 0, 0.15);
}

.rules-info p {
	margin: 0 0 1.5vw 0;
	font-size: 3.5vw;
	color: #856404;
	line-height: 1.6;
	font-weight: 500;
}

.rules-info p:last-child {
	margin-bottom: 0;
}

.fee-note {
	font-size: 3vw !important;
	opacity: 0.9;
}

/* 提现计算结果 */
.withdraw-summary {
	background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
	border-radius: 2.5vw;
	padding: 4vw;
	margin: 5vw 0;
	border: 2px solid #e0e7ff;
	box-shadow: 0 4px 16px rgba(0, 0, 0, 0.08);
}

.summary-item {
	display: flex;
	justify-content: space-between;
	align-items: center;
	padding: 2.5vw;
	margin-bottom: 2vw;
	font-size: 3.5vw;
	color: #666;
	background: #fff;
	border-radius: 1.5vw;
	transition: all 0.3s;
}

.summary-item:hover {
	box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
	transform: translateX(2px);
}

.summary-item:last-child {
	margin-bottom: 0;
}

.summary-item.total {
	border-top: 2px solid #e0e7ff;
	padding-top: 3vw;
	margin-top: 3vw;
	font-size: 4.5vw;
	font-weight: 600;
	color: #333;
	background: linear-gradient(135deg, #fff 0%, #f0f4ff 100%);
}

.fee-text {
	color: #e74c3c;
	font-weight: 600;
	font-size: 4vw;
}

.deduct-text {
	color: #ff9800;
	font-weight: 600;
	font-size: 4vw;
}

.total-text {
	color: #667eea;
	font-weight: 700;
	font-size: 5vw;
	text-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
}

/* 提现方式 */
.withdraw-methods h3 {
	margin: 5vw 0 4vw 0;
	font-size: 4.5vw;
	color: #333;
	font-weight: 600;
	display: flex;
	align-items: center;
}

.withdraw-methods h3::before {
	content: '';
	width: 4px;
	height: 4vw;
	background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
	border-radius: 2px;
	margin-right: 2vw;
}

.method-list {
	list-style: none;
	padding: 0;
	margin: 0;
}

.method-list li {
	display: flex;
	align-items: center;
	padding: 4vw 3vw;
	border: 2px solid #e0e0e0;
	border-radius: 2.5vw;
	margin-bottom: 3vw;
	cursor: pointer;
	transition: all 0.3s;
	position: relative;
	background: #fff;
	box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.method-list li:last-child {
	margin-bottom: 0;
}

.method-list li:hover {
	border-color: #667eea;
	background: linear-gradient(135deg, #f0f4ff 0%, #e8f0ff 100%);
	transform: translateY(-2px);
	box-shadow: 0 4px 16px rgba(102, 126, 234, 0.2);
}

.method-list li.selected {
	border-color: #667eea;
	background: linear-gradient(135deg, #e6f0ff 0%, #d6e8ff 100%);
	box-shadow: 0 4px 20px rgba(102, 126, 234, 0.3);
}

.method-list li img {
	width: 10vw;
	height: 10vw;
	margin-right: 3vw;
	border-radius: 1vw;
	box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.method-list li .fa-university {
	font-size: 6vw;
	color: #667eea;
	margin-right: 3vw;
	width: 10vw;
	height: 10vw;
	display: flex;
	align-items: center;
	justify-content: center;
	background: linear-gradient(135deg, #f0f4ff 0%, #e8f0ff 100%);
	border-radius: 1vw;
}

.method-list li span {
	flex: 1;
	font-size: 4vw;
	color: #333;
	font-weight: 500;
}

.method-list li .fa-check-circle {
	font-size: 5vw;
	color: #52c41a;
	opacity: 0;
	transition: all 0.3s;
	background: #fff;
	border-radius: 50%;
	padding: 1vw;
	box-shadow: 0 2px 8px rgba(82, 196, 26, 0.3);
}

.method-list li.selected .fa-check-circle {
	opacity: 1;
	transform: scale(1.1);
}

/* 提现备注 */
.withdraw-notes {
	margin-top: 5vw;
}

.withdraw-notes textarea {
	width: 100%;
	border: 2px solid #e0e0e0;
	border-radius: 2vw;
	padding: 3.5vw;
	font-size: 3.5vw;
	color: #333;
	min-height: 18vw;
	resize: vertical;
	box-sizing: border-box;
	background: linear-gradient(135deg, #fafafa 0%, #ffffff 100%);
	transition: all 0.3s;
}

.withdraw-notes textarea:focus {
	outline: none;
	border-color: #667eea;
	box-shadow: 0 4px 16px rgba(102, 126, 234, 0.15);
	background: #fff;
}

.withdraw-notes textarea::placeholder {
	color: #ccc;
}

.note-count {
	text-align: right;
	font-size: 3vw;
	color: #999;
	margin-top: 1.5vw;
}

/* 操作按钮 */
.action-buttons {
	display: flex;
	gap: 3vw;
	margin: 4vw 3vw;
	position: sticky;
	bottom: 0;
	z-index: 10;
}

.action-buttons button {
	flex: 1;
	padding: 4.5vw 3vw;
	border: none;
	border-radius: 2.5vw;
	font-size: 4vw;
	cursor: pointer;
	transition: all 0.3s;
	font-weight: 600;
	box-shadow: 0 4px 16px rgba(0, 0, 0, 0.2);
	display: flex;
	align-items: center;
	justify-content: center;
}

.cancel-btn {
	background: linear-gradient(135deg, #f5f5f5 0%, #e9ecef 100%);
	color: #666;
}

.cancel-btn:hover {
	background: linear-gradient(135deg, #e9ecef 0%, #dee2e6 100%);
	transform: translateY(-2px);
	box-shadow: 0 6px 20px rgba(0, 0, 0, 0.25);
}

.cancel-btn:active {
	transform: translateY(0);
}

.confirm-btn {
	background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
	color: #fff;
	position: relative;
	overflow: hidden;
}

.confirm-btn::before {
	content: '';
	position: absolute;
	top: 0;
	left: -100%;
	width: 100%;
	height: 100%;
	background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.3), transparent);
	transition: left 0.5s;
}

.confirm-btn:hover:not(:disabled)::before {
	left: 100%;
}

.confirm-btn:hover:not(:disabled) {
	background: linear-gradient(135deg, #7c8ef0 0%, #8a5fb8 100%);
	transform: translateY(-2px);
	box-shadow: 0 6px 24px rgba(102, 126, 234, 0.4);
}

.confirm-btn:active:not(:disabled) {
	transform: translateY(0);
}

.confirm-btn:disabled {
	background: #ccc;
	cursor: not-allowed;
	box-shadow: none;
}

/* 加载和错误状态 */
.loading {
	text-align: center;
	padding: 8vw;
	color: #fff;
	font-size: 4vw;
	position: relative;
}

.loading::before {
	content: '';
	display: inline-block;
	width: 8vw;
	height: 8vw;
	border: 4px solid rgba(255, 255, 255, 0.3);
	border-top: 4px solid #fff;
	border-radius: 50%;
	animation: spin 1s linear infinite;
	margin-right: 2vw;
	vertical-align: middle;
}

@keyframes spin {
	0% { transform: rotate(0deg); }
	100% { transform: rotate(360deg); }
}

.error-msg {
	background: linear-gradient(135deg, #fff5f5 0%, #ffe0e0 100%);
	margin: 4vw 3vw;
	border-radius: 2.5vw;
	padding: 4vw;
	text-align: center;
	box-shadow: 0 4px 16px rgba(231, 76, 60, 0.2);
	border: 2px solid #ffcdd2;
}

.error-msg p {
	margin: 0;
	color: #e74c3c;
	font-size: 3.5vw;
	font-weight: 500;
}
</style>
